<!--
 * @Descripttion:
 * @version:
 * @Author: Connor
 * @Date: 2021-04-07 19:27:24
 * @LastEditors: Sam
 * @LastEditTime: 2021-07-02 10:43:56
-->
<template>
  <el-container class="m-container">
    <el-header class="m-header" height="50px" style="line-height:50px">
      <el-row>
        <el-col :span="5" sytle="float:left">
          <el-button
            size="mini"
            class="left-btn"
            @click="bacthEdit()"
            type="primary"
            >批量审核</el-button
          >
          <el-button
            size="mini"
            class="export-btn"
            @click="exportTab()"
            type="primary"
          >导出流水信息(当前页)</el-button
          >
          <span>&nbsp;</span>
        </el-col>

        <el-col :span="19">
          <el-form ref="queryForm" :model="queryForm" class="query-form">
            <el-select
              size="mini"
              class="query-form-item"
              v-model="queryForm.customerId"
              filterable
              clearable
              remote
              :remote-method="remoteMethod"
              placeholder="输入客户"
            >
              <el-option
                v-for="item in serachCustomerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <el-select
              size="mini"
              class="query-form-item"
              v-model="queryForm.statementStatus"
              filterable
              placeholder="选择状态"
            >
              <el-option
                v-for="item in statusList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <el-select
              size="mini"
              class="query-form-item"
              v-model="queryForm.statementType"
              filterable
              placeholder="选择类型"
            >
              <el-option
                v-for="item in typeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <el-input
              size="mini"
              class="query-form-item"
              clearable
              @keypress.enter.native="querydata()"
              v-model="queryForm.bankStatementAmount"
              placeholder="金额"
            ></el-input>
            <el-date-picker
              size="mini"
              v-model="queryForm.cdate"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="创建时间开始"
              end-placeholder="创建时间结束"
              align="right"
            >
            </el-date-picker>
            <el-button-group>
              <el-button
                size="mini"
                class="left-btn"
                type="primary"
                icon="el-icon-search"
                @click="querydata()"
                >搜索</el-button
              >
              <el-button size="mini" class="right-btn" @click="resetData()"
                >重置</el-button
              >
            </el-button-group>
          </el-form>
        </el-col>
      </el-row>
    </el-header>
    <el-main class="m-main">
      <el-table
        :data="tableData"
        id="out-table"
        tooltip-effect="light"
        style="width: 99%"
        size="mini"
        @selection-change="handleSelectionChange"
      >
        <el-table-column :selectable="filterStatus" type="selection" width="30">
        </el-table-column>
        <el-table-column fixed prop="customerName" label="客户" width="180">
        </el-table-column>
        <el-table-column
          fixed
          prop="bankStatementAmount"
          label="流水金额"
          width="120"
        >
        </el-table-column>
        <el-table-column prop="currency" label="水币币种" width="80">
        </el-table-column>
        <el-table-column prop="typeName" label="类型" width="80">
        </el-table-column>
        <el-table-column prop="statusName" label="状态" width="80">
        </el-table-column>
        <el-table-column label="充值图片" width="120">
          <template slot-scope="scope">
            <el-link
              v-if="scope.row.imageUrl.indexOf('.pdf') != -1"
              type="primary"
              :href="scope.row.imageUrl"
              >pdf下载</el-link
            >
            <el-image
              v-else
              style="width:60px;height:60px"
              fit="contain"
              :src="scope.row.imageUrl"
              lazy
              :preview-src-list="scope.row.imageUrlList"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column label="客户备注">
          <template slot-scope="scope">
            <div v-html="scope.row.customerRemark"></div>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="saleBillName" label="来源" width="120">
        </el-table-column>
        <el-table-column prop="userName" label="创建人" width="120">
        </el-table-column>
        <el-table-column prop="cdate" label="创建时间" width="150">
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.statementStatus == 0"
              @click="editRow(scope.row)"
              type="primary"
              icon="el-icon-edit"
              size="mini"
              >审核</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-dialog title="批量审核" :visible.sync="bacthDialogFormVisible">
        <el-table
          :data="multipleSelection"
          tooltip-effect="light"
          style="width: 100%"
          size="mini"
        >
          <el-table-column fixed prop="bankStatementAmount" label="流水金额">
          </el-table-column>
          <el-table-column label="充值图片">
            <template slot-scope="scope">
              <el-image
                style="width:60px;height:40px"
                fit="contain"
                :src="scope.row.imageUrl"
                lazy
                :preview-src-list="scope.row.imageUrlList"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" show-overflow-tooltip>
          </el-table-column>
        </el-table>
        <el-form
          ref="bacthCheckForm"
          :model="bacthCheckForm"
          label-width="120px"
        >
          <el-form-item label="增加新备注">
            <el-input
              type="textarea"
              v-model="bacthCheckForm.newRemark"
            ></el-input>
          </el-form-item>
          <el-button
            size="mini"
            class="right-btn"
            @click="resetBacthCheckForm()"
            >取消</el-button
          >
          <el-button size="mini" type="danger" @click="bacthUpdateStatus(-1)"
            >不通过</el-button
          >
          <el-button
            size="mini"
            class="left-btn"
            type="primary"
            @click="bacthUpdateStatus(1)"
            >通过</el-button
          >
        </el-form>
      </el-dialog>

      <el-dialog title="审核" :visible.sync="oneDialogFormVisible">
        <el-form ref="checkForm" :model="checkForm" label-width="120px">
          <el-form-item label="流水金额(RMB)">
            {{ checkForm.bankStatementAmount }}
          </el-form-item>
          <el-form-item label="流水图片">
            <el-image
              style="width:60px;height:60px"
              fit="contain"
              :src="checkForm.imageUrl"
              :preview-src-list="checkForm.imageUrlList"
            ></el-image>
          </el-form-item>
          <el-form-item label="备注">
            {{ checkForm.remark }}
          </el-form-item>
          <el-form-item label="增加新备注">
            <el-input type="textarea" v-model="checkForm.newRemark"></el-input>
          </el-form-item>
          <el-button size="mini" class="right-btn" @click="resetCheckForm()"
            >取消</el-button
          >
          <el-button size="mini" type="danger" @click="updateStatus(-1)"
            >不通过</el-button
          >
          <el-button
            size="mini"
            class="left-btn"
            type="primary"
            @click="updateStatus(1,checkForm.saleBillId,checkForm.bankStatementAmount)"
            >通过</el-button
          >
        </el-form>
      </el-dialog>
    </el-main>
    <el-footer class="m-footer" height="45px">
      <el-row>
        <el-col :span="22">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[20, 50, 100, 300, 500]"
            :page-size="20"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            style="padding-top: 10px;"
          >
          </el-pagination>
        </el-col>
        <el-col :span="2"></el-col>
      </el-row>
    </el-footer>
  </el-container>
</template>
<script>
import { ajax } from "@/store/yg/common/utils";
import { m } from "@/store/yg/common/local";
import * as constant from "@/store/yg/common/constant";
import FileSaver from "file-saver";
import XLSX from "xlsx";
export default {
  components: {},
  props: [],
  data() {
    return {
      fullscreenLoading: false,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      currentPage: 1,
      pageSize: 20,
      total: 0,
      multipleSelection: [],
      queryForm: {
        customerId: "",
        statementStatus: "",
        urgencytype: "",
        bankStatementAmount: "",
        cdate: [],
        userId: ""
      },
      customerList: [],
      loading: false,
      serachCustomerList: [],
      statusList: [],
      typeList: [],
      tableData: [],
      userId: "",
      bacthDialogFormVisible: false,
      oneDialogFormVisible: false,
      checkForm: {
        newRemark: ""
      },
      bacthCheckForm: {
        newRemark: ""
      }
    };
  },
  mounted() {
    this.querydata();
    this.userId = parseInt(this.$store.state.auth.user.id);
  },
  methods: {
    async querydata() {
      this.queryForm["currentPage"] = this.currentPage;
      this.queryForm["pageSize"] = this.pageSize;
      this.queryForm.userId = this.$store.state.auth.user.id;
      const data = await ajax("pageList", this.queryForm);
      console.log(data);
      var list = data.data;
      if (list && list.length > 0) {
        list.forEach(element => {
          element.statusName = m(data.statusMap[element.statementStatus]);
          element.typeName = m(data.typeMap[element.statementType]);
          element.userName = data.userMap[element.cuser];
          element.customerName = data.customerMap[element.customerId];
          if (element.statementBillType != 2) {
            element.saleBillName = "业务账单上传";
          } else {
            element.saleBillName = "客户账单上传";
          }
          if (element.rechargePicture) {
            element.imageUrl = constant.FILE_SERVER + element.rechargePicture;
            element.imageUrlList = [
              constant.FILE_SERVER + element.rechargePicture
            ];
          }
        });
      }
      this.customerList = [];
      this.statusList = [];
      this.typeList = [];
      if (data.customerMap) {
        for (const key in data.customerMap) {
          let customer = {
            id: key,
            name: data.customerMap[key]
          };
          this.customerList.push(customer);
        }
      }
      if (data.statusMap) {
        for (const key in data.statusMap) {
          let status = {
            id: key,
            name: m(data.statusMap[key])
          };
          this.statusList.push(status);
        }
      }
      if (data.typeMap) {
        for (const key in data.typeMap) {
          let type = {
            id: key,
            name: m(data.typeMap[key])
          };
          this.typeList.push(type);
        }
      }
      this.tableData = list;
      this.total = data.count;
    },
    exportTab(){
      /* 从表生成工作簿对象 */
      var id="#out-table";
      var fix = document.querySelector('.el-table__fixed');
      var wb;
      if (fix) {
        wb = XLSX.utils.table_to_book(document.querySelector(id).removeChild(fix));
        document.querySelector(id).appendChild(fix);
      } else {
        wb = XLSX.utils.table_to_book(document.querySelector(id));
      }
      debugger
      /* 获取二进制字符串作为输出 */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        FileSaver.saveAs(
          //Blob 对象表示一个不可变、原始数据的类文件对象。
          //Blob 表示的不一定是JavaScript原生格式的数据。
          //File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
          //返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
          new Blob([wbout], { type: "application/octet-stream" }),
          //设置导出文件名称
          "流水信息.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    filterStatus(row, index) {
      if (row.statementStatus != 0) {
        return false;
      } else {
        return true;
      }
    },
    remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.serachCustomerList = this.customerList.filter(item => {
            return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1;
          });
        }, 300);
      } else {
        this.serachCustomerList = [];
      }
    },
    resetData() {
      this.queryForm = {
        customerId: "",
        statementStatus: "",
        urgencytype: "",
        bankStatementAmount: "",
        cdate: [],
        userId: ""
      };
      this.currentPage = 1;
      this.pageSize = 20;
      this.querydata();
    },
    handleSizeChange(val) {
      //console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.querydata();
    },
    handleCurrentChange(val) {
      //console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.querydata();
    },
    handleSelectionChange(rows) {
      var list = [];
      if (rows.length > 0) {
        rows.forEach(data => {
          if (data.statementStatus == 0) {
            list.push(data);
          }
        });
      }
      this.multipleSelection = list;
      //console.log(this.multipleSelection);
    },
    async bacthEdit() {
      if (this.multipleSelection.length == 0) {
        this.$notify.error({
          title: "错误",
          message: "请选择数据"
        });
        return false;
      }
      this.bacthDialogFormVisible = true;
    },
    resetBacthCheckForm() {
      this.bacthDialogFormVisible = false;
      this.bacthCheckForm = {
        newRemark: ""
      };
      //this.multipleSelection = [];
    },
    async bacthUpdateStatus(status) {
      let ids = [];
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach(element => {
          ids.push(element.id);
        });
      }
      const param = {
        ids: ids,
        statementStatus: status,
        remark: this.bacthCheckForm.newRemark,
        userId: this.userId
      };
      const data = await ajax("saveStatement", param);
      console.log("data", data);
      if (data.code == 200) {
        this.$notify.success({ title: "正确", message: "提交成功" });
        this.querydata();
        this.resetBacthCheckForm();
      } else {
        this.$notify.error(date.message);
      }
    },
    editRow(row) {
      this.oneDialogFormVisible = true;
      this.checkForm = {
        id: row.id,
        bankStatementAmount: row.bankStatementAmount,
        imageUrl: row.imageUrl,
        imageUrlList: row.imageUrlList,
        remark: row.remark,
        saleBillId: row.saleBillId
      };
      //this.checkForm.newRemark = "";
    },
    resetCheckForm() {
      this.oneDialogFormVisible = false;
      this.checkForm = {
        newRemark: ""
      };
    },
    async updateStatus(status,id,bankStatementAmount) {
      const param = {
        ids: [this.checkForm.id],
        statementStatus: status,
        remark: this.checkForm.newRemark,
        userId: this.userId
      };
      const data = await ajax("saveStatement", param);
      //console.log("data",data);
      if (data.code == 200) {
        this.$notify.success({ title: "正确", message: "提交成功" });
        this.querydata();
        this.resetCheckForm();
        if (status==1) {
          window.open("/#/blank/finance__account__main?customerBillIdStrs=" + id+"&bankStatementAmount="+bankStatementAmount);
        }
      } else {
        this.$notify.error(date.message);
      }
    }
  }
};
</script>
<style>
.el-container {
  background-color: rgb(233, 238, 243);
  padding: 0;
  margin: 0;
}
.m-header,
.m-footer {
  box-sizing: border-box;
  flex-shrink: 0;
  padding: 0px 20px;
  font-size: 12px;
  text-align: left;
  padding: 0;
  margin: 0;
}
.m-main {
  background-color: #fff;
  padding: 0;
  margin: 0;
}
.left-btn {
  color: rgb(255, 255, 255);
  background-color: rgb(42, 144, 188);
  border-color: rgb(42, 144, 188);
}
.right-btn {
  background: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
}
.query-form {
  text-align: right;
}
.query-form-item {
  width: 120px;
}
.message-link-div {
  text-align: center;
}
.message-link-div >>> a {
  color: blue;
}
.message-link-div >>> a:hover {
  text-decoration: underline;
}
</style>
